package com.cygsunri.solar.api;

import com.alibaba.fastjson.JSON;
import com.cygsunri.common.constant.DataName;
import com.cygsunri.common.constant.DeviceType;
import com.cygsunri.common.entity.DeviceInfo;
import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.measurement.calculate.AbstractComplexEndureCalculateService;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.multienergy.api.dto.HisData;
import com.cygsunri.multienergy.api.dto.HisDataList;
import com.cygsunri.scada.base.BasePSR;
import com.cygsunri.scada.service.ScadaPSRService;
import com.cygsunri.solar.config.CurveConfig;
import com.cygsunri.solar.dto.SolarParams;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 光伏页api新版本
 */

@RestController
@RequestMapping("/api/v2/solar")
public class SolarV2Controller {

    @Value("${corsair.yc.step}")
    private Integer ycStep;

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private ScadaPSRService scadaPSRService;

    @Autowired
    private AbstractComplexEndureCalculateService abstractComplexEndureCalculateService;

    @Autowired
    private CurveConfig curveConfig;

    /**
     * 逆变器运行状态
     *
     * @param deviceId 光伏PSRID
     */
    @GetMapping(value = "/statistics/substations/inverters")
    public ResponseEntity<List<DeviceInfo>> invertersInfo(@RequestParam("deviceId") String deviceId) {
        List<DeviceInfo> deviceInfoList = new ArrayList<>();
        List<BasePSR> inverters = scadaPSRService.getDeviceOfSubstationByType(deviceId, DeviceType.INVERTER.getKey());
        for (BasePSR inverter : inverters) {
            ImmutablePair<String, String> pair = abstractComplexEndureCalculateService.getDeviceStatusPair(inverter.getId());
            DeviceInfo deviceInfo = new DeviceInfo()
                    .setPsrID(inverter.getId())
                    .setName(inverter.getName())
                    .setType(DeviceType.INVERTER.getName())
                    .setStatus(pair == null ? null : pair.getRight());

            List<Map<String, String>> list = new ArrayList<>();

            MeasurementValue outPower = commonDataService.getValue(inverter.getId(), DataName.OUT_POWER);
            MeasurementValue dayGenerated = commonDataService.getValue(inverter.getId(), DataName.DAY_GENERATED);

            Map<String, String> m1 = Maps.newHashMap();
            m1.put("name", DataName.OUT_POWER);
            m1.put("data", outPower.isInValid() ? "-" : String.valueOf(outPower.getData()));
            list.add(m1);

            Map<String, String> m2 = Maps.newHashMap();
            m2.put("name", DataName.DAY_GENERATED);
            m2.put("data", dayGenerated.isInValid() ? "-" : String.valueOf(dayGenerated.getData()));
            list.add(m2);

            deviceInfo.setExtra(list);
            deviceInfoList.add(deviceInfo);
        }

        return new ResponseEntity<>(deviceInfoList, HttpStatus.OK);
    }


    /**
     * 光伏功率与辐照度曲线
     *
     * @param deviceId 光伏PSRID
     * @param date yyyy-mm-dd
     */
    @PostMapping(value = "/charts/substations/power")
    public ResponseEntity<String> solarPower(@RequestBody SolarParams solarParams) {

        HisDataList retDataList = new HisDataList();

        BasePSR substation = scadaPSRService.getDeviceByPsrId(solarParams.getDeviceId());
        if (substation == null) {
            return new ResponseEntity<>(JSON.toJSONString(retDataList), HttpStatus.NOT_FOUND);
        }

        List<MeasurementValue> powerValues = commonDataService.getHistoryValue(solarParams.getDeviceId(), DataName.TOTAL_ACTIVE_POWER, curveConfig.buildBeginTime(solarParams.getDate()), curveConfig.buildEndTime(solarParams.getDate()), ycStep, 2, false);

        List<BasePSR> weathers = scadaPSRService.getDeviceOfSubstationByType(solarParams.getDeviceId(), DeviceType.WEATHER_INC.getKey());

        List<MeasurementValue> radiationValues;

        HisData outPowerData = new HisData();
        outPowerData.setName("功率");
        outPowerData.setUnit("kW");
        HisData radiationData = new HisData();
        radiationData.setName("辐照");
        radiationData.setUnit("");

        for (MeasurementValue outPower : powerValues) {

            retDataList.getTimeRange().add(outPower.getTime());
            outPowerData.getData().add(outPower.isInValid() ? "-" : outPower.getData().toString());
        }

        if (!weathers.isEmpty()) {
            radiationValues = commonDataService.getHistoryValue(weathers.get(0).getId(), DataName.TOTAL_RADIATION, curveConfig.buildBeginTime(solarParams.getDate()), curveConfig.buildEndTime(solarParams.getDate()), ycStep, 2, false);
            for (MeasurementValue radiation : radiationValues) {

                radiationData.getData().add(radiation.isInValid() ? "-" : radiation.getData().toString());
            }
        }

        retDataList.getRecords().add(outPowerData);
        retDataList.getRecords().add(radiationData);

        return new ResponseEntity<>(JSON.toJSONString(retDataList), HttpStatus.OK);
    }
}
